package com.rzx.mybackend.service.Impl;

import com.rzx.mybackend.service.TokenService;
import com.rzx.mybackend.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

/**
 * TokenServiceImpl
 *
 * @author renzhexian
 * @date 2025/7/15
 */
@Service
@RequiredArgsConstructor
public class TokenServiceImpl implements TokenService {

    @Value("${jwt.secret-key}")
    private String secretKey;

    /*
    验证token有效性
     */
    @Override
    public void verifyToken(HttpServletRequest request) {
        // 获取token
        String authorization = request.getHeader("Authorization");
        if (authorization == null || authorization.isEmpty()) {
            // 如果token为空，抛出异常
            throw new RuntimeException("请求头未携带token，无法登录！");
        }
        // 解析token
        Claims claims = JwtUtil.parseJWT(secretKey, authorization);
        /*
        验证token有效性
         */
        String username = claims.get("userName", String.class); // 用户名

        if (username == null || username.isEmpty()) {
            // 如果用户信息为空，说明token解析失败
            throw new RuntimeException("token解析失败，无法登录！");
        }

        // 设置认证信息到SecurityContext (如果不认证到UsernamePasswordAuthenticationToken，SpringSecurity会认为无权限，后续会报403)
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(username, null,Collections.emptyList());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}
